﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.DBModule;
using ZX.BLL;
using ZX.EHR.Library;
using ZX.DAL.DBExtend;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using ZX.Common;
using ZX.BLL.Extend;

namespace ZX.EHR.Web
{
    public partial class hrExaminationAjax : BasePage
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            string flag = this.GetStringFromQueryString("flag", "");
            switch (flag.ToLower())
            {
                case "saveexaminationitemtype":
                    SaveExaminationItemType();
                    break;
                case "delexaminationitemtype":
                    DelExaminationItemType();
                    break;
                case "delexaminationitem":
                    DelExaminationItem();
                    break;
                case "createitemtypeselect":
                    CreateItemTypeSelect();
                    break;
                case "createitemselect":
                    CreateItemSelect();
                    break;
                case "createstandardselect":
                    CreateStandardSelect();
                    break;
                case "savestandard":
                    SaveStandard();
                    break;
                case "deleexaminationplan":
                    DeleExaminationPlan();
                    break;
                case "saveexaminationobjectbypost":
                    SaveExaminationObjectByPost();
                    break;
                case "saveexaminationrole":
                    SaveExaminationRole();
                    break;
                case "savebathexaminationrole":
                    SaveBathExaminationRole();
                    break;
                case "savesorce":
                    SaveSorce();
                    break;
                case "isappraisefinish":
                    IsAppraiseFinish();
                    break;
                case "roleisappraisefinish":
                    RoleIsAppraiseFinish();
                    break;

                default:
                    break;
            }
        }

        #region 分类
        /// <summary>
        /// 保存考核项目分类
        /// </summary>
        public void SaveExaminationItemType()
        {
            try
            {
                string strJson = this.GetStringFromQueryString("json", "");
                BDatPhraseDetail bc = new BDatPhraseDetail();
                BaseBussnies bll = new BaseBussnies();
                V_ExaminationItemType instance = (V_ExaminationItemType)Globals.JSonToObject<V_ExaminationItemType>(strJson);
                //IList<V_ExaminationItemType> instance = Globals.JSonToObject<IList<V_ExaminationItemType>>(strJson);

                //分类序号
                int seq = GetExaminationItemTypeSeq();
                if (bc.GetDatPhraseDetailByPhrasaeTextAndClassId(instance.PhraseText, new Guid(instance.ClassID.ToString()), new Guid("00000000-0000-0000-0000-000000000000"), 0))
                {
                    HttpContext.Current.Response.Write("该类型名称已经存在!");
                    return;
                }
                else
                {
                    string strSql = string.Format("insert into DatPhraseDetail(PhraseText,PhraseValue,ClassID,IsPause,IsLock,Seq,IsDefault) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
                                                instance.PhraseText, seq, instance.ClassID, "False", "False", seq, "False");
                    int result = bll.RunSqlCommand(strSql);
                    if (result > 0)
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("保存失败!");
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("保存失败!");
            }
        }

        /// <summary>
        /// 取得项目分类序号
        /// </summary>
        /// <returns></returns>
        public int GetExaminationItemTypeSeq()
        {
            int seq = 1;
            string sql = "select max(seq) seq from DatPhraseDetail where ClassID=(select ClassID from DatPhraseClass where ClassValue='ExaminationItemType')";
            DbSql dbsql = new DbSql();
            seq = dbsql.ExecuteScalar(sql);
            seq++;
            return seq;
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        public void DelExaminationItemType()
        {
            try
            {
                string id = this.GetStringFromQueryString("id", "");
                if (id == string.Empty)
                {
                    HttpContext.Current.Response.Write("ID为空"); //ID为空
                    return;
                }
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                string condition = "";
                bool isDelete = true;
                //定义引用表
                string[] tableName = { "ExaminationItem" };
                //先查询是否被引用了，如果有引用则不能删除，给提示
                foreach (string s in tableName)
                {
                    instance = ZX.Common.Globals.getEntity(s) as BaseEntity;
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    condition = string.Format("CateoryID ='{0}'", id);
                    isDelete = (baseBll.GetEntityByCondition(condition) == null);
                    if (!isDelete) { break; }
                }
                if (isDelete)
                {
                    //删除主表
                    instance = ZX.Common.Globals.getEntity("DatPhraseDetail") as BaseEntity;
                    condition = string.Format("PhraseID ='{0}'", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("有引用则不能删除");  //有引用则不能删除
                    return;
                }


            }
            catch(Exception ex)
            {
                HttpContext.Current.Response.Write("删除失败:"+ex.ToString());
            }
        }
        #endregion

        #region 项目
        /// <summary>
        /// 删除项目
        /// </summary>
        public void DelExaminationItem()
        {
            try
            {
                string id = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");

                if (id == string.Empty)
                {
                    HttpContext.Current.Response.Write("ID为空"); //ID为空
                    return;
                }
                id = "'" + id.Replace(",", "','") + "'";
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                string condition = "";
                bool isDelete = true;
                //定义引用表
                string[] tableName = { "ExaminationPlan" };
                //先查询是否被引用了，如果有引用则不能删除，给提示
                foreach (string s in tableName)
                {
                    instance = ZX.Common.Globals.getEntity(s) as BaseEntity;
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    condition = string.Format("SolutionID in ({0})", id);
                    isDelete = (baseBll.GetEntityByCondition(condition) == null);
                    if (!isDelete) break;
                }
                if (isDelete)
                {
                    //删除方案考核标准表
                    instance = ZX.Common.Globals.getEntity("ExaminationStandard") as BaseEntity;
                    condition = string.Format("SolutionID  in ({0})", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);

                    //删除方案项目子表
                    instance = ZX.Common.Globals.getEntity("ExaminationSolutionItem") as BaseEntity;
                    condition = string.Format("SolutionID  in ({0})", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);

                    //删除主表
                    instance = ZX.Common.Globals.getEntity("ExaminationSolution") as BaseEntity;
                    condition = string.Format("ID  in ({0})", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("有引用则不能删除");  //有引用则不能删除
                    return;
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }
        }

        /// <summary>
        /// 保存方案考核标准
        /// </summary>
        public void SaveStandard()
        {
            try
            { 
                string strJson = this.GetStringFromQueryString("json", "");
                BaseBussnies bll = null;
                IList<ExaminationStandard> lstInstance = Globals.JSonToObject<IList<ExaminationStandard>>(strJson);

                //先删除
                BaseEntity examinationStandard = ZX.Common.Globals.getEntity("ExaminationStandard") as BaseEntity;
                string condition = string.Format("SolutionID in ('{0}')", lstInstance[0].SolutionID.ToString());
                bll = new ZX.BLL.Extend.BaseBussnies(examinationStandard);
                bll.delete(condition);
                foreach (ExaminationStandard instance in lstInstance)
                {
                    bll = new BaseBussnies(instance);
                    instance.ID = Guid.NewGuid();
                    instance.AddTime = DateTime.Now;
                    instance.AddUser = Guid.Parse(User.AddUser.ToString());
                    bll.Insert();
                }
                HttpContext.Current.Response.Write("1");
            }
            catch(Exception ex)
            {
                HttpContext.Current.Response.Write("保存失败!" + ex.Message);
            }
        }

        #endregion

        #region 生成下拉框
        /// <summary>
        /// 考核标准下拉框
        /// </summary>
        public void CreateStandardSelect()
        {
            string sql = @"select PhraseText as DisplayMember,CONVERT(varchar(120),PhraseID)+'|'+PhraseValue as ValueMember  from DatPhraseDetail 
                            where ClassID=(select ClassID from DatPhraseClass where ClassValue='ExaminationStandard')
                            order by Seq";
            CreateSelect(sql);
        }

        /// <summary>
        /// 项目分类下拉框
        /// </summary>
        public void CreateItemTypeSelect()
        {
            string sql = @"select PhraseID as ValueMember,PhraseText as DisplayMember from V_ExaminationItemType 
                            where ClassID !='00000000-0000-0000-0000-000000000000'
                            order by PhraseText";
            CreateSelect(sql);
        }
        /// <summary>
        /// 根据分类ID,生成项目下拉框
        /// </summary>
        /// <param name="cateoryID"></param>
        public void CreateItemSelect()
        {
            string cateoryID = this.GetStringFromQueryString("cateoryID", "");
            string sql = @"select ID as ValueMember,ItemName as DisplayMember from ExaminationItem 
                            where 1=1 and CateoryID='{0}'
                            order by ItemName";
            CreateSelect(string.Format(sql, cateoryID));
        }

        /// <summary>
        /// 创建下拉框
        /// </summary>
        /// <param name="sql"></param>
        public void CreateSelect(string sql)
        {
            DbSql dbsql = new DbSql();
            DataTable dt = dbsql.ExecuteQuery(sql);
            string option = "<option value='{0}' {2}>{1}</option>";
            string options = "";
            foreach (DataRow dr in dt.Rows)
            {
                options += string.Format(option, dr["ValueMember"].ToString(), dr["DisplayMember"].ToString(), "");
            }
            HttpContext.Current.Response.Write(options);
        }
        #endregion

        #region 计划
        /// <summary>
        /// 删除考核计划
        /// </summary>
        public void DeleExaminationPlan()
        {
            try
            {
                string id = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");

                if (id == string.Empty)
                {
                    HttpContext.Current.Response.Write("ID为空"); //ID为空
                    return;
                }
                id = "'" + id.Replace(",", "','") + "'";
                BaseEntity instance = null;
                ZX.BLL.Extend.BaseBussnies baseBll = null;
                string condition = "";
                bool isDelete = true;
                //定义引用表
                string[] tableName = { "ExaminationObject","ExaminationResult" };
                //先查询是否被引用了，如果有引用则不能删除，给提示
                foreach (string s in tableName)
                {
                    instance = ZX.Common.Globals.getEntity(s) as BaseEntity;
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    condition = string.Format("PlanID in ({0})", id);
                    isDelete = (baseBll.GetEntityByCondition(condition) == null);
                    if (!isDelete) break;
                }
                if (isDelete)
                {

                    //删除主表
                    instance = ZX.Common.Globals.getEntity("ExaminationPlan") as BaseEntity;
                    condition = string.Format("ID  in ({0})", id);
                    baseBll = new ZX.BLL.Extend.BaseBussnies(instance);
                    baseBll.delete(condition);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("有引用则不能删除");  //有引用则不能删除
                    return;
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write("e" + e.Message);
            }

        }

        #endregion

        #region 生成个人考核表
        /// <summary>
        /// 通过岗位批量生成对应的个人考核表
        /// </summary>
        public void SaveExaminationObjectByPost()
        {
            string ids = this.GetStringFromQueryString("ids", "");
            string nams = this.GetStringFromQueryString("nams", "");
            string planID = this.GetStringFromQueryString("selectPlanID", "");
            try
            {
                ExaminationObject instance = ZX.Common.Globals.getEntity("ExaminationObject") as ExaminationObject;
                BaseBussnies bll = new BaseBussnies(instance);
                string sql = "select * from V_hrEmployee where PostID='{0}'";
                DbSql dbsql = new DbSql();
                DataTable dt = new DataTable();
                //新增
                foreach (string id in ids.Split(','))
                {
                    instance.PostID = Guid.Parse(id);
                    instance.PlanID = Guid.Parse(planID);
                    dt = dbsql.ExecuteQuery(string.Format(sql, id));
                    foreach (DataRow dr in dt.Rows)
                    {
                        instance.EmployeeID = Guid.Parse(dr["ID"].ToString());
                        //先删除
                        bll.delete(string.Format(" PlanID ='{0}' and EmployeeID='{1}'", planID, dr["ID"].ToString()));
                        bll.Insert();
                    }
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }
        }

        #endregion

        #region 保存考核角色
        /// <summary>
        /// 批量保存考核角色
        /// </summary>
        public void SaveBathExaminationRole()
        {
            try
            {
                string strJson = this.GetStringFromQueryString("json", "");
                string ids = this.GetStringFromQueryString("objectIDs", "");
                IList<ExaminationRole> lstInstance = Globals.JSonToObject<IList<ExaminationRole>>(strJson);
                foreach (string id in ids.Split(','))
                {
                    SaveExaminationRole(id, lstInstance);
                }
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("保存失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 保存考核角色，只保存为单个被考核者设置的考核角色
        /// </summary>
        public void SaveExaminationRole()
        {
            try
            {
                string strJson = this.GetStringFromQueryString("json", "");
                string id = this.GetStringFromQueryString("id", "");
                IList<ExaminationRole> lstInstance = Globals.JSonToObject<IList<ExaminationRole>>(strJson);
                if (SaveExaminationRole(id, lstInstance))
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存失败!");
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("保存失败!" + ex.Message);
            }
        }

        /// <summary>
        /// 保存考核角色，只保存为单个被考核者设置的考核角色
        /// </summary>
        /// <param name="objectId">考核对象</param>
        /// <param name="lstInstance">ExaminationRole对象集合</param>
        public bool SaveExaminationRole(string objectId, IList<ExaminationRole> lstInstance)
        {
            bool result = false;
            try
            {
                BaseBussnies bll = null;
                string condition = "ObjectID = '{0}' and EmployeeID='{1}'";
                string sql = "update ExaminationRole set Weight='{0}' where {1}";                
                bool isExist = false;
                DbSql dbsql = new DbSql();
                //先删除未考核的角色
                dbsql.ExecuteSql(string.Format("delete from ExaminationRole where ObjectID = '{0}' and IsAppraise='N'", objectId));
                foreach (ExaminationRole instance in lstInstance)
                {
                    bll = new BaseBussnies(instance);
                    isExist = (dbsql.ExecuteScalar(string.Format("select count(*) from ExaminationRole where {0}", string.Format(condition, objectId, instance.EmployeeID.ToString()))) == 1);
                    if (!isExist)
                    {
                        instance.ID = Guid.NewGuid();
                        instance.ObjectID = Guid.Parse(objectId);
                        instance.IsAppraise = "N";
                        instance.AddTime = DateTime.Now;
                        instance.AddUser = Guid.Parse(User.AddUser.ToString());
                        bll.Insert();
                    }
                    else
                    {
                        dbsql.ExecuteSql(string.Format(sql, instance.Weight, string.Format(condition, objectId, instance.EmployeeID.ToString())));
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;

        }

        #endregion

        #region 保存考核打分
        /// <summary>
        /// 保存考核打分
        /// </summary>
        /// <param name="?"></param>
        public void SaveSorce()
        {
            string planID = this.GetStringFromQueryString("planID", "");
            string solutionID = this.GetStringFromQueryString("solutionID", "");
            string effectDate = this.GetStringFromQueryString("effectDate", "");
            string examinationor = this.GetStringFromQueryString("examinationor", "");
            string employeeID = this.GetStringFromQueryString("employeeID", "");
            string strJson = this.GetStringFromQueryString("json", "");
            string roleID = this.GetStringFromQueryString("roleID", "");
            string objectID = this.GetStringFromQueryString("objectID", "");

            string sql = "update ExaminationRole set IsAppraise='Y' where ID='{0}'";
            DbSql dbsql = new DbSql();

            try
            {
                IList<ExaminationResult> lstInstance = Globals.JSonToObject<IList<ExaminationResult>>(strJson);
                BaseBussnies bll = null;
                string condition = "RoleID='{0}' and ItemID='{1}'  ";
                foreach (ExaminationResult instance in lstInstance)
                {
                    bll = new BaseBussnies(instance);
                    instance.ID = Guid.NewGuid();
                    instance.EmployeeID = Guid.Parse(employeeID);
                    instance.EffectDate = DateTime.Parse(effectDate);
                    instance.PlanID = Guid.Parse(planID);
                    instance.SolutionID = Guid.Parse(solutionID);
                    instance.Examinationor = Guid.Parse(examinationor);
                    instance.RoleID = Guid.Parse(roleID);
                    instance.AddTime = DateTime.Now;
                    //先删除
                    bll.delete(string.Format(condition, roleID, instance.ItemID.ToString()));
                    bll.Insert();
                    //更新考核角色表状态，标识已考核
                    dbsql.ExecuteSql(string.Format(sql, roleID));
                }
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("-1");
            }

        }

        #endregion

        #region 判断是否考核完毕
        /// <summary>
        /// 判断一个考核计划是否考核完毕，即所有考核者都打分了。
        /// </summary>
        public void IsAppraiseFinish()
        {
            string objectID = this.GetStringFromQueryString("objectID", "");

            string sql1 = string.Format("select COUNT(*) as TotalRoleNum from ExaminationRole where ObjectID='{0}'", objectID);
            string sql2 = string.Format("select COUNT(*) as FinishRoleNum from ExaminationRole where ObjectID='{0}' and IsAppraise='Y'", objectID);

            DbSql dbsql = new DbSql();
            int TotalRoleNum = 0, FinishRoleNum = 0;
            try
            {
                TotalRoleNum = dbsql.ExecuteScalar(sql1);
                FinishRoleNum = dbsql.ExecuteScalar(sql2);
                if (TotalRoleNum == FinishRoleNum)
                {
                    HttpContext.Current.Response.Write("Y");
                }
                else
                {
                    HttpContext.Current.Response.Write("N");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("N");
            }
        }

        /// <summary>
        /// 判断某个考核角色是否已经给某个考核计划打分了
        /// </summary>
        public void RoleIsAppraiseFinish()
        {
            string objectID = this.GetStringFromQueryString("objectID", "");
            string roleEmpID = this.GetStringFromQueryString("roleEmpID", "");

            string sql = string.Format("select COUNT(*) as FinishRoleNum from ExaminationRole where ObjectID='{0}' and EmployeeID='{1}' and IsAppraise='Y'", objectID, roleEmpID);

            DbSql dbsql = new DbSql();
            int  FinishRoleNum = 0;
            try
            {
                FinishRoleNum = dbsql.ExecuteScalar(sql);
                if (FinishRoleNum == 1)
                {
                    HttpContext.Current.Response.Write("Y");
                }
                else
                {
                    HttpContext.Current.Response.Write("N");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("N");
            }
        }
        #endregion

    }
}